package com.rbac.admin.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.admin.entity.system.SysOperationLog;
import com.rbac.admin.mapper.system.SysOperationLogMapper;
import com.rbac.admin.service.system.SysOperationLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 系统操作日志Service实现类
 * 
 * @author RBAC-Admin
 * @since 2024-01-01
 */
@Slf4j
@Service
public class SysOperationLogServiceImpl extends ServiceImpl<SysOperationLogMapper, SysOperationLog> 
        implements SysOperationLogService {

    @Override
    public IPage<SysOperationLog> selectLogPage(Long current, Long size, String username, 
                                               String roleName, String operationModule, String operationType, 
                                               Integer operationResult, String startTime, String endTime) {
        
        Page<SysOperationLog> page = new Page<>(current, size);
        return baseMapper.selectLogPage(page, username, roleName, operationModule, operationType, 
                                      operationResult, startTime, endTime);
    }

    @Override
    public int cleanOldLogs(int days) {
        try {
            LocalDateTime beforeDate = LocalDateTime.now().minusDays(days);
            
            LambdaQueryWrapper<SysOperationLog> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.lt(SysOperationLog::getCreateTime, beforeDate);
            
            int count = (int) this.count(queryWrapper);
            this.remove(queryWrapper);
            
            log.info("清理{}天前的操作日志，共清理{}条记录", days, count);
            return count;
            
        } catch (Exception e) {
            log.error("清理操作日志失败", e);
            return 0;
        }
    }
}